package yl.hs.bmipfull.service.system.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.system.ICoreDataTagDao;
import yl.hs.bmipfull.daos.system.ISiteMessageMainDao;
import yl.hs.bmipfull.daos.system.ISiteMessageReceiptDao;
import yl.hs.bmipfull.daos.system.IUserInfoDao;
import yl.hs.bmipfull.pojo.system.RoleInfoEntity;
import yl.hs.bmipfull.pojo.system.SiteMessageMainEntity;
import yl.hs.bmipfull.pojo.system.SiteMessageReceiptEntity;
import yl.hs.bmipfull.pojo.system.UserInfoEntity;
import yl.hs.bmipfull.service.system.ISiteMessageReceiptService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.MsgReceiveType;
import yl.hs.bmipfull.utils.datastate.MsgType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.system.MsgModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作用:  站内信息收件信息服务层接口实现<br/>
 * 创建时间: 2021年05月12日 16时32分18秒 <br/>
 *
 * @author 张凯
 */
@Service
public class SiteMessageReceiptServiceImpl extends SystemBaseService implements ISiteMessageReceiptService {

    @Autowired
    ISiteMessageReceiptDao dao;
    @Autowired
    IUserInfoDao userInfoDao;
    @Autowired
    ISiteMessageMainDao messageMainDao;
    @Autowired
    ICoreDataTagDao coreDataTagDao;


    @Override
    public List<SiteMessageReceiptEntity> queryAll() {
        return dao.queryAll();
    }
    @Override
    public Map<String,Object> getTypeCount(PageQuery pageQuery, int rowNum, int page){
        Map<String,Object> result=new HashMap<>();
        pageQuery.getQuery().put("querySkip", page);
        pageQuery.getQuery().put("pageSize", rowNum);
        var user= HsApp.getCurrent();
        var tags = coreDataTagDao.queryBySN(user.getUserSN().split(","));
        var roleCode = Tl.getDBMapCode(RoleInfoEntity.class);
        var roles = tags.stream().filter(p -> p.getTagType().equals(roleCode) && p.getMainSN().equals(user.getUserSN())).map(p -> p.getTagSN()).collect(Collectors.toList());
        String sql="(";
        sql=sql+"receipterSN like '%"+user.getUserSN()+"%'";

        if(roles.size()>0){
            for (var roleSn: roles) {
                sql=sql+"or receipterSN like '%"+roleSn+"%'";
            }
        }
        if(user.getDutySN()!=null && !user.getDutySN().equals("") && user.getDutySN().split(",").length>0){
            for (var dutySn: user.getDutySN().split(",")) {
                sql=sql+"or receipterSN like '%"+dutySn+"%'";
            }
        }
        if(user.getOrganizationCode()!=null&& !user.getOrganizationCode().equals("") && user.getOrganizationCode().split(",").length>0){
            for (var organizationCode: user.getOrganizationCode().split(",")) {
                sql=sql+"or receipterSN like '%"+organizationCode+"%'";
            }
        }
        sql=sql+")";
        pageQuery.getQuery().put("userSql",sql);
        var list=dao.queryPage(pageQuery.getQuery());
        var all=dao.queryCountByCondition(pageQuery.getQuery());
        var system=0;
        var flow=0;
        var bulletin=0;
        var instant=0;
        var systemhd=0;
        var flowhd=0;
        var bulletinhd=0;
        var instanthd=0;
        for (var entity:list) {
            var map=entity.toMap();
            var messageMain=messageMainDao.findBySN(entity.getMsgSN());
            if (messageMain.getMsgType()==MsgType.System.code){
                system+=1;
                if(entity.getState()==0){
                    systemhd+=1;
                }
            }else if (messageMain.getMsgType()==MsgType.Flow.code){
                flow+=1;
                if(entity.getState()==0){
                    flowhd+=1;
                }
            }else if (messageMain.getMsgType()==MsgType.Bulletin.code){
                bulletin+=1;
                if(entity.getState()==0){
                    bulletinhd+=1;
                }
            }else if (messageMain.getMsgType()==MsgType.Instant.code){
                instant+=1;
                if(entity.getState()==0){
                    instanthd+=1;
                }
            }
        }
        result.put("all",all);
        result.put("system",system);
        result.put("flow",flow);
        result.put("bulletin",bulletin);
        result.put("instant",instant);
        result.put("systemhd",systemhd);
        result.put("flowhd",flowhd);
        result.put("bulletinhd",bulletinhd);
        result.put("instanthd",instanthd);
        return result;
    }
    @Override
    public PageResult<Map<String,Object>> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(SiteMessageReceiptEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<Map<String,Object>> result = new PageResult(rowNum);

//        pageQuery.getQuery().put("userSn",user.getUserSN());
//        if(user.getRoleSN()!=null && user.getRoleSN().length>0){
//            pageQuery.getQuery().put("roleSn",user.getRoleSN());
//        }
//        if(user.getDutySN()!=null && !user.getDutySN().equals("") && user.getDutySN().split(",").length>0){
//            pageQuery.getQuery().put("dutySN",user.getDutySN().split(","));
//        }
//        if(user.getOrganizationCode()!=null&& !user.getOrganizationCode().equals("") && user.getOrganizationCode().split(",").length>0){
//            pageQuery.getQuery().put("organizationCode",user.getOrganizationCode().split(","));
//        }
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery()));
        result.setPage(page);
        var list=dao.queryPage(pageQuery.getQuery());
        List<Map<String,Object>> resultMap=new ArrayList<>();
        for (var entity:list) {
            var map=entity.toMap();
            var messageMain=messageMainDao.findBySN(entity.getMsgSN());
            map.put("messageMain",messageMain);
            resultMap.add(map);
        }
        result.setData(resultMap);
        return result;
    }

    @Override
    public PageResult<Map<String, Object>> queryPageSite(PageQuery pageQuery, int rowNum, int page,String sn) throws Exception {
        pageQuery.checkSortSides(SiteMessageReceiptEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<Map<String,Object>> result = new PageResult(rowNum);
        String sql="(receipterSN like '%"+sn+"%')";
        pageQuery.getQuery().put("userSql",sql);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery()));
        result.setPage(page);
        var list=dao.queryPage(pageQuery.getQuery());
        List<Map<String,Object>> resultMap=new ArrayList<>();
        for (var entity:list) {
            var map=entity.toMap();
            var messageMain=messageMainDao.findBySN(entity.getMsgSN());
            map.put("messageMain",messageMain);
            resultMap.add(map);
        }
        result.setData(resultMap);
        return result;
    }


    @Override
    public List<SiteMessageReceiptEntity> findByMsgSN(String msgSN) {
        return dao.queryByCondition("msgSN = '" + msgSN + "'");
    }

    public MsgReceiveType returnMsgReceiveTypeByShort(short type){
        if (MsgReceiveType.User.code==type){
            return MsgReceiveType.User;
        }else if(MsgReceiveType.Role.code==type){
            return MsgReceiveType.Role;
        }else if(MsgReceiveType.Duty.code==type){
            return MsgReceiveType.Duty;
        }else if(MsgReceiveType.Organize.code==type){
            return MsgReceiveType.Organize;
        }else{
            return MsgReceiveType.User;
        }
    }
    @Override
    @Transactional
    public Integer saveSiteMessageReceipt(MsgModel msgModel) throws Exception {
        Integer result = 0;
        if(msgModel.getMsgType()==MsgType.Bulletin.code){
            result =sendMsg(MsgType.Bulletin,returnMsgReceiveTypeByShort(msgModel.getReceiverType()),msgModel.getToUserSn(), msgModel.getTitle(), msgModel.getMsgBody());
        }else if (msgModel.getMsgType()==MsgType.Instant.code){
            result =sendMsg(MsgType.Instant,returnMsgReceiveTypeByShort(msgModel.getReceiverType()),msgModel.getToUserSn(), msgModel.getTitle(), msgModel.getMsgBody());
        }else{
            result =sendMsg(MsgType.Instant,returnMsgReceiveTypeByShort(msgModel.getReceiverType()),msgModel.getToUserSn(), msgModel.getTitle(), msgModel.getMsgBody());
        }

        return result;

//        SiteMessageMainEntity mainEntity = messageMainDao.findBySN(msgSn);
//        for (int i = 0; i < userSns.length; i++) {
//            UserInfoEntity userInfo = userInfoDao.findBySN(userSns[0]);
//            SiteMessageReceiptEntity receiptEntity = new SiteMessageReceiptEntity();
//            receiptEntity.setMsgSN(msgSn);
//            receiptEntity.setReceiptType(Short.valueOf(receiptTypes[0]));
//            receiptEntity.setReceiptTime(mainEntity.getSendTime());
//            receiptEntity.setReceipterSN(userInfo.getSn());
//            receiptEntity.setReceipterName(userInfo.getAccount());
//            result += dao.insertNew(receiptEntity);
//        }
    }


    @Override
    public List<SiteMessageReceiptEntity> findByUserSn(String userSn) {
        var user= HsApp.getCurrent();

        var tags = coreDataTagDao.queryBySN(user.getUserSN().split(","));
        var roleCode = Tl.getDBMapCode(RoleInfoEntity.class);
        var roles = tags.stream().filter(p -> p.getTagType().equals(roleCode) && p.getMainSN().equals(user.getUserSN())).map(p -> p.getTagSN()).collect(Collectors.toList());
        String sql="(";
        sql=sql+"receipterSN like '%"+user.getUserSN()+"%'";

        if(roles.size()>0){
            for (var roleSn: roles) {
                sql=sql+"or receipterSN like '%"+roleSn+"%'";
            }
        }
        if(user.getDutySN()!=null && !user.getDutySN().equals("") && user.getDutySN().split(",").length>0){
            for (var dutySn: user.getDutySN().split(",")) {
                sql=sql+"or receipterSN like '%"+dutySn+"%'";
            }
        }
        if(user.getOrganizationCode()!=null&& !user.getOrganizationCode().equals("") && user.getOrganizationCode().split(",").length>0){
            for (var organizationCode: user.getOrganizationCode().split(",")) {
                sql=sql+"or receipterSN like '%"+organizationCode+"%'";
            }
        }
        sql=sql+")";
        return dao.queryByCondition(sql);
    }

    @Override
    @Transactional
    public Integer receipt(String[] msgSn, String userSn) throws Exception {
        Integer result = 0;
        for (String sn : msgSn) {

            SiteMessageReceiptEntity receiptEntity = dao.findByCondition("msgSN = '" + sn + "' and receipterSN = '" + userSn + "'");
            receiptEntity.setState((short) 1);
            if (dao.update(receiptEntity) > 0) {
                result++;
                writeLog(ActionType.UPDATE, sn, "信息已读", receiptEntity.toJson(), SiteMessageReceiptEntity.class);
            }

        }
        return result;
    }

    @Override
    public Integer queryUnReadMessageCount(String userSN) {
        return dao.queryUnReadCountByUserSN(userSN, DataState.UNREAD.code);
    }


}